#include "ff.h"
#include <string.h>
#include "my_log.h"



extern const uint8_t test_data[];

void test_wirte_speed(void);
FRESULT scan_files(char *path);

FATFS fs;
static char pRootDir[30] = "\\";

FIL file;

void fatfs_test(void)
{
    FRESULT res;
    UINT w_size;
    res = f_mount(&fs, pRootDir, 1);

    if(res != FR_OK)
    {
        log_i("f_mount err: %d", res);
    }

    log_i("f_mount OK");

    res = f_open(&file, "\\Hello0.txt", FA_OPEN_ALWAYS | FA_WRITE);

    if(res != FR_OK)
    {
        log_i("f_open err: %d", res);
    }

    res = f_write(&file, "Hello world", sizeof("Hello world"), &w_size);

    if(res != FR_OK)
    {
        log_i("f_write err: %d", res);
    }

    f_close(&file);

    log_i("****************  Test write speed *****************");
    test_wirte_speed();
    
    log_i("mkdir");
    res = f_mkdir("\\file");
    if(res != FR_OK)
    {
        log_i("f_mkdir err: %d", res);
    }
    
    log_i("Now create file in second dir");
    res = f_open(&file, "\\file\\Test2.txt", FA_OPEN_ALWAYS | FA_WRITE);
    f_close(&file);
    
    log_i("\r\n List dir \r\n");
    scan_files(pRootDir);
}

static char *pTestFile = "\\test.txt";

void test_wirte_speed(void)
{
    FRESULT res;
    UINT w_size;

    res = f_open(&file, pTestFile, FA_OPEN_ALWAYS | FA_WRITE);

    if(res != FR_OK)
    {
        log_i("f_open err: %d", res);
    }

    uint32_t startCount = HAL_GetTick();
    uint32_t endCount = 0;

    for(int i = 0; i < 25; i++)
    {
        res = f_write(&file, test_data, 4096, &w_size);

        if(res != FR_OK)
        {
            log_i("f_write err: %d", res);
        }
    }

    f_close(&file);

    endCount = HAL_GetTick();

    log_i("Write:\t %d Bytes", 5120 * 20);
    log_i("Use:\t %d ms", endCount - startCount);
    log_i("Speed:\t %f Kbyte/s", 5120 * 20.0 / (endCount - startCount) / 1024 * 1000);
}


FRESULT scan_files(char *path)
{

    FRESULT res;

    FILINFO fno;

    DIR dir;

    int i;

    char *fn;

#if _USE_LFN

    static char lfn[_MAX_LFN * (_DF1S ? 2 : 1) + 1];

    fno.lfname = lfn;

    fno.lfsize = sizeof(lfn);

#endif



    res = f_opendir(&dir, path);

    if(res == FR_OK)
    {

        i = strlen(path);

        for(;;)
        {

            res = f_readdir(&dir, &fno);

            if(res != FR_OK || fno.fname[0] == 0)
            {
                break;
            }

            if(fno.fname[0] == '.')
            {
                continue;
            }

#if _USE_LFN

            fn = *fno.lfname ? fno.lfname : fno.fname;

#else

            fn = fno.fname;

#endif

            if(fno.fattrib & AM_DIR)
            {

                sprintf(&path[i], "\%s", fn);

                res = scan_files(path);

                if(res != FR_OK)
                {
                    break;
                }

                path[i] = 0;

            }
            else
            {

                log_i("%s\\%s\n", path, fn);

            }

        }

    }


    return res;

}

